﻿using Library.Core.Domain;
using Library.Core.Domain.Specification;
using Synthesize.BaseSet.Domain.Aggregation.Entity.Authority;
using Synthesize.BaseSet.Domain.Repository.Authority;
using System.Threading.Tasks;

namespace Synthesize.BaseSet.Domain.Specifications.Authority.Menu
{
    public class UpdateMenuSpecification : IOperateSpecification<MenuInfoEntity>
    {
        private readonly IMenuRepository _menuRepository;

        public UpdateMenuSpecification(IMenuRepository menuRepository)
        {
            _menuRepository = menuRepository;
        }
        public async Task<bool> SatisfiedBy(MenuInfoEntity entity)
        {
            if (!await _menuRepository.AnyAsync(x => x.Id == entity.Id))
            {
                throw new DomainException("无对应菜单信息！");
            }
            if (await _menuRepository.AnyAsync(x => x.Title.Equals(entity.Title) && x.ParentId.Equals(entity.ParentId) && !x.Id.Equals(entity.Id)))
            {
                throw new DomainException("同一层级下,菜单名称重复");
            }
            if (entity.Id.Equals(entity.ParentId))
            {
                throw new DomainException("不能以自己作为上级菜单");
            }
            return true;
        }
    }
}
